<template>
  <div>
    <div class="header">
      <el-input
        class="input"
        placeholder="用户名"
        v-model="searchObj.username"
      ></el-input>
      <el-button
        @click="getUsers()"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button icon="el-icon-search" @click="clear">清空</el-button>
    </div>

    <div class="margin">
      <el-button type="primary" @click="addUser">添加</el-button>
      <el-button type="danger" @click="delAll" :disabled="!ids.length"
        >批量删除</el-button
      >

      <el-table
        :data="users"
        class="margin"
        border
        ref="table"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="序号" type="index"> </el-table-column>
        <el-table-column label="用户名" prop="username"> </el-table-column>
        <el-table-column label="用户名称" prop="nickName"> </el-table-column>
        <el-table-column label="权限列表" prop="roleName"> </el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate"> </el-table-column>
        <el-table-column label="更新时间" prop="gmtModified"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="info"
              size="mini"
              icon="el-icon-user"
              @click="setUser(row)"
              title="设置角色"
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editUserInfo(row)"
              title="修改角色"
            ></el-button>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @onConfirm="removeUser(row)"
            >
              <el-button
                style="margin-left: 10px"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                slot="reference"
                title="删除角色"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="text-align: center"
        class="margin"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[3, 5, 7, 9]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加用户 -->
    <el-dialog
      :title="!user.id ? '添加用户' : '修改用户'"
      :visible.sync="addUserDialogVisible"
      width="50%"
    >
      <span slot="footer" class="dialog-footer">
        <el-form :model="user" :rules="userRules" ref="userRef">
          <el-form-item label="用户名" prop="username" label-width="120px">
            <el-input v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item
            label="用户名称"
            :prop="!user.id ? 'nickName' : ''"
            label-width="120px"
          >
            <el-input v-model="user.nickName"></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            v-if="!user.id"
            prop="password"
            label-width="120px"
          >
            <el-input v-model="user.password"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色 -->
    <el-dialog
      title="设置角色"
      :visible.sync="setUserDialogVisible"
      width="50%"
      @close="setUserDialogClosed"
    >
      <span slot="footer" class="dialog-footer">
        <el-form ref="setUserRef">
          <el-form-item label="用户名" label-width="80px">
            <el-input :value="user.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色列表" label-width="80px">
            <el-checkbox
              v-loading="checkboxLoading"
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group v-model="assignRoles">
              <el-checkbox
                v-for="role in allRolesList"
                :key="role.id"
                :label="role.id"
                >{{ role.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="saveRoleName">保 存</el-button>
        <el-button @click="setUserDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      page: 1,
      limit: 3,
      searchObj: {
        username: "",
      },
      users: [],
      total: 0,
      loading: false,
      addUserDialogVisible: false,
      // 收集用户信息
      user: {},
      // 表单验证规则
      userRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
      setUserDialogVisible: false,
      // 控制checkbox样式
      isIndeterminate: true,
      // 所有角色列表权限
      allRolesList: [],
      // 设置角色id
      assignRoles: [],
      // 全选
      checkAll: false,
      // 存储多个角色id
      ids: [],
      checkboxLoading: false,
      // 存储点击时的用户id
      userId: 0,
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    async getUsers() {
      this.loading = true;
      const { page, limit, searchObj } = this;
      const res = await this.$Api.user.getPageList(page, limit, searchObj);
      if (res.code == 20000) {
        this.loading = false;
        this.users = res.data.items;
        this.total = res.data.total;
      }
    },
    async handleSelectionChange(selection) {
      if (!selection.length) {
        this.ids = [];
      } else {
        this.ids = selection.map((item) => item.id);
      }
    },
    // 批量删除
    async delAll() {
      const Result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => this.$message.info("取消了删除"));
      if (Result == "confirm") {
        const res = await this.$Api.user.removeUsers(this.ids);
        console.log(res);
      }
    },
    handleSizeChange(newPageNum) {
      this.limit = newPageNum;
      this.getUsers();
    },
    handleCurrentChange(newPage) {
      this.page = newPage;
      this.getUsers();
    },
    // 清空
    clear() {
      this.searchObj = {};
      this.getUsers();
    },
    // 点击添加或者修改的弹出层
    addUser() {
      this.user = {};
      this.addUserDialogVisible = true;
    },
    // 添加或者修改用户之后的确认按钮
    addOrUpdate() {
      this.$refs.userRef.validate(async (valid) => {
        if (valid) {
          const res = await this.$Api.user[!this.user.id ? "add" : "update"](
            this.user
          );
          if (res.code == 20000) {
            this.addUserDialogVisible = false;
            this.$message.success("保存成功");
            this.getUsers();
          }
        }
      });
    },
    // 修改用户信息
    async editUserInfo(row) {
      this.user = {};
      const res = await this.$Api.user.getById(row.id);
      if (res.code == 20000) {
        this.user = res.data.item;
        this.addUserDialogVisible = true;
      }
    },
    // 删除某个用户
    async removeUser(row) {
      await await this.$Api.user.removeById(row.id);
      this.$message.success("删除成功");
      this.getUsers();
    },
    // 获取角色身份
    async setUser(row) {
      this.checkboxLoading = true;
      this.user = row;
      this.userId = row.id;
      this.setUserDialogVisible = true;
      const res = await this.$Api.user.getRoles(row.id);
      if (res.code == 20000) {
        this.checkboxLoading = false;
        const { allRolesList, assignRoles } = res.data;
        this.allRolesList = allRolesList;
        this.assignRoles = assignRoles.map((item) => item.id);
      }
    },
    // 点击分配角色全选事件
    handleCheckAllChange(value) {
      this.isIndeterminate = value;

      this.isIndeterminate
        ? (this.assignRoles = this.allRolesList.map((item) => item.id))
        : (this.assignRoles = []);
    },
    // 关闭设置角色窗口的事件
    setUserDialogClosed() {
      this.$nextTick(() => {
        this.assignRoles = [];
        this.allRolesList = [];
      });
    },
    async saveRoleName() {
      const roleId = this.assignRoles.join(",");
      const res = await this.$Api.user.assignRoles(this.userId, roleId);
      if (res.code == 20000) {
        this.$message.success("保存成功");
        this.setUserDialogVisible = false;
        this.getUsers();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  display: flex;

  .input {
    width: 250px;
  }
}
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  padding-top: 30px;

  .el-checkbox {
    width: 80px;
    display: inline-block;
    text-align: justify;
    text-justify: distribute-all-lines;
    text-align-last: justify;
  }
}

.el-checkbox:last-of-type {
  float: left;
}
</style>
